﻿#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion


#region Using directives

using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using ZO.SmartCore.Configuration.Properties;
using ZO.SmartCore.IO;
using ArgumentException= ZO.SmartCore.Core.ArgumentException;
using ArgumentNullException= ZO.SmartCore.Core.ArgumentNullException;

#endregion

namespace ZO.SmartCore.Configuration
{
    internal static class Utility
    {

        #region Constructors

        #endregion

        #region Destructor

        #endregion

        #region Fields

        #endregion

        #region Events

        #endregion

        #region Operators

        #endregion

        #region Properties

        #endregion

        #region Methods
        /// <summary>Returns a Boolean indicating whether the specified file exists.</summary>
        /// <param name="file">String. Name and path of the file. Required. </param>
        /// <param name="throwException">throw exception if this is true</param>
        [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        public static bool FileExists(string file, bool throwException)
        {
            bool ret = false;
            if (!String.IsNullOrEmpty(file) && (file.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.OrdinalIgnoreCase) || file.EndsWith(Path.AltDirectorySeparatorChar.ToString(), StringComparison.OrdinalIgnoreCase)))
            {
                return ret;
            } // if


            ret = File.Exists(file);
            if (!ret)
            {
                if (throwException)
                {
                    throw new FileNotFoundException(String.Format(CultureInfo.InvariantCulture, Resources.IO_FileNotFound_Path, new string[] { file }), file);
                }
            } // if
            return ret;
        } // FileExists

        private static void CheckFilePathTrailingSeparator(string path, string paramName)
        {
            if (String.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(paramName);
            } // if
            if (path.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal) | path.EndsWith(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                throw new ArgumentException(paramName);
            } // if
        } // CheckFilePathTrailingSeparator

        /// <summary>Returns the contents of a file as a byte array.</summary>
        /// <returns>Byte array containing the contents of the file.</returns>
        /// <param name="file">String. File to be read. Required. </param>
        public static string ReadAllText(string file)
        {
            return File.ReadAllText(file);
        } // ReadAllText

        /// <summary>
        /// Reads the file into memory.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns></returns>
        public static StringStream ReadFileIntoStream(string file)
        {
            if (File.Exists(file))
            {
                return new StringStream(ReadAllText(file));
            }
            return null;
        } // ReadIntoMemory

        /// <summary>
        /// Writes the file from memory.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="contents">The contents.</param>
        public static void WriteFileFromStream(string file, StringStream contents)
        {
            byte[] data = contents.ToArray();

            WriteAllText(file, data, false);
        } // WriteFileFromStream


        /// <summary>Writes data to a binary file.</summary>
        /// <param name="file">String. Path and name of the file to be written to. Required. </param>
        /// <param name="data">Byte. Data to be written to the file. Required. </param>
        /// <param name="append">Boolean. Whether to append or overwrite data. Default is False. Required. </param>
        public static void WriteAllText(string file, byte[] data, bool append)
        {
            if (String.IsNullOrEmpty(file))
            {
                throw new ArgumentNullException("file");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            CheckFilePathTrailingSeparator(file, "file");

            FileMode mode1;

            string dir = Path.GetDirectoryName(file);
            if (append)
            {
                mode1 = FileMode.Append;
            } // if
            else
            {
                mode1 = FileMode.Create;

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            } // else

            using (FileStream stream1 = new FileStream(file, mode1, FileAccess.Write, FileShare.Read))
            {

                stream1.Write(data, 0, data.Length);
            } // using
        } // WriteAllText
        #endregion
    }
}
